<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssignPer(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDelRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="queryParams.page"
                :page-sizes="[2, 4, 6, 8]"
                :page-size="queryParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 编辑角色  -->
    <el-dialog :title="isEdit? '编辑角色' : '添加角色'" :visible.sync="showDialog" :close-on-click-modal="false" @close="resetRoleFrom">
      <el-form ref="roleForm" :model="roleForm" label-width="100px" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
        <el-button style="margin-left:50%" size="small" @click="showDialog=false">取消</el-button>
        <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
      </el-form>
    </el-dialog>
    <!-- 角色分配权限 -->
    <el-dialog v-if="showDialogPer" title="权限" :visible.sync="showDialogPer">
      <assignPermission :id="curId" @cancel="showDialogPer=false" />
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, delRole, updateRole } from '@/api/settings'
import assignPermission from './assignPermission.vue'
export default {
  name: 'Setting',
  components: {
    assignPermission
  },
  data() {
    return {
      curId: '',
      showDialogPer: false,
      isEdit: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      showDialog: false,
      queryParams: {
        page: 1,
        pagesize: 2
      },
      list: [], // 保存角色列表
      total: 0
    }
  },
  created() {
    this.loadRoleList()
  },
  methods: {
    hAssignPer(id) {
      this.curId = id
      this.showDialogPer = true
    },
    // 清空表单
    resetRoleFrom() {
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 删除角色
    hDelRole(id) {
      this.$confirm('确认删除这个角色吗?, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRole(id)
        if (this.list.length === 1) {
          this.queryParams.page--
          // console.log(this.queryParams.page, '-------1-------')
        }
        if (this.queryParams.page === 0) this.queryParams.page = 1
        this.loadRoleList()
        console.log(22)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 打开编辑角色
    hEdit(data) {
      // console.log(data)
      this.isEdit = true
      this.showDialog = true
      this.roleForm = { ...data }
      // console.log(this.roleForm, '=======')
    },
    // 打开添加角色
    hAdd() {
      this.isEdit = false
      this.showDialog = true
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 确认编辑角色
    async doEdit() {
      try {
        await updateRole(this.roleForm)
        // console.log(res)
        this.showDialog = false
        this.loadRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    // 确认添加角色
    async doAdd() {
      try {
        await addRole(this.roleForm)
        this.total++
        const pageMax = Math.ceil(this.total / this.queryParams.pagesize)
        this.queryParams.page = pageMax
        // console.log(pageMax)
        this.loadRoleList()
        this.isEdit = false
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 确认添加角色 or 确认编辑
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return // 错误的情况
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 分页器
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.page = 1
      this.queryParams.pagesize = val
      this.loadRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryParams.page = val
      this.loadRoleList()
    },
    // h获取所有角色列表
    async loadRoleList() {
      try {
        // console.log(this.queryParams.page, '-------222-------')

        const res = await getRoleList(this.queryParams)
        this.list = res.data.rows
        this.total = res.data.total
        // console.log(res)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
